// pages/publish/index.js
import CommunityModule from '../../models/3.0/community'
import { Message } from '../../models/message'
import UploadImg from '../../util/uploadImg'
const uploadImg = new UploadImg()

Page({
  "tabBar": {
    "list": [  
      { "pagePath": "pages/explore/explore",
    "text": "发现",
    "iconPath": "static/images/tab-bar/recruit0.png",
    "selectedIconPath": "static/images/tab-bar/recruit1.png"}
  ]
  },
  data: {
    fileList: [],
    topic: [],
    community: {
      name: '选择圈子',
      id: 0
    },
    Address:'',
    contentText: '',
    video:'',
    videoimage:'',
    imgList: [],          // 上传列表
    src: "",   
  },

  publish() {
    if (!this.data.contentText || this.data.community.name==='选择圈子') {
      wx.showToast({
        title: '请选择圈子填写内容'
      })
      return
    }
    CommunityModule.publishMoment({
      coverUrl:this.data.videoimage,
      content: this.data.contentText,
      position: this.data.Address,
      userId: wx.getStorageSync('userInfo').user_id || 0,
      type: this.data.video?'1':'0',
      momentsGroupId: this.data.community.id,
      topicId: this.data.topic.map((i) => i.id).join(),
      topicName: this.data.topic.map((i) => i.topicName).join(),
      images:this.data.fileList.map(i=>i.url).join()|| this.data.video
    }).then((res) => {
      wx.showToast({
        title: '发布成功'
      })
      wx.switchTab({
        url: '/pages/explore/explore'
      })
      console.log(this.data.Address);
    })

  },


  onInput(e){
    let textVal = e.detail.value;
    this.setData({
      contentText:textVal
    })
  },

  // 失去焦点时
  onBlur() {
    console.log("失去焦点时");
  },


  chooseLocation() {
    let that = this
    wx.chooseLocation({
      success(res) { 
        that.setData({
          'Address': res.name
        })
      }
    })
  },
  // 上传图片
  chooseSource: function () {
    var _this = this;
    wx.showActionSheet({
      itemList: ["拍照", "从相册中选择"],
      itemColor: "#000000",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            _this.imgWShow("camera")     //拍照
          } else if (res.tapIndex == 1) {
            _this.imgWShow("album")      //相册
          }
        }
      }
    })
  },
  // 点击调用手机相册/拍照
  imgWShow: function (type) {
    var _this = this;
    let len = 0;
    if (_this.data.imgList != null) {
      len = _this.data.imgList.length
    }   //获取当前已有的图片
    console.log(len);
    wx.chooseImage({
      // count: 3 - len,     //最多还能上传的图片数,这里最多可以上传5张
      count: 9 - len,
      sizeType: ['original', 'compressed'],        //可以指定是原图还是压缩图,默认二者都有
      sourceType: [type],             //可以指定来源是相册还是相机, 默认二者都有
      success: function (res) {
        // 判断是否合法
        wx.uploadFile({
          url: 'http://192.168.0.195:8291/wxAppletUser/checkIsLegalImage',
          filePath: res.tempFilePaths.join(),
          method: "POST",
          name: 'file',
          formData: {
            len: res.tempFiles.length,
            mediaType: 2,
            urlArr: res.tempFilePaths
          },
          success: function(res) {
            console.log(res);
            
          },
          fail: function(err) {
            console.log(err);
            return false
          }
        })
        // http://192.168.0.195:8291/wxAppletUser/checkIsLegalImage
        wx.showToast({
          title: '正在上传...',
          icon: "loading",
          mask: true,
          duration: 1000
        })
        // 返回选定照片的本地文件路径列表,tempFilePaths可以作为img标签的scr属性显示图片
        var imgList = res.tempFilePaths
        let tempFilePathsImg = _this.data.imgList
        // 获取当前已上传的图片的数组
        var tempFilePathsImgs = tempFilePathsImg.concat(imgList)
        // console.log(tempFilePathsImgs);
        _this.setData({
          imgList: tempFilePathsImgs
        })
      wx.uploadFile({
      url: 'http://192.168.0.195:8291/OnLoad/uploadFile', 
      filePath: imgList.join(),
      method:'POST',
      name: 'file',
      mutiple:true,
      formData: { user: 'test' },
      success(res) {
        console.log(11111);
        // 上传完成需要更新 fileList
        const { fileList = [] } = _this.data;
        res.data = JSON.parse(res.data).data
        fileList.push({ ...imgList, url: res.data });
        _this.setData({ fileList,
         });
           },
       });
      },
      fail: function () {
        wx.showToast({
          title: '图片上传失败',
          icon: 'none'
        })
        return;
      }
    })
  },
  // 预览图片
  previewImg: function (e) {
    let index = e.mark.oid;
    let _this = this;
    wx.previewImage({
      current: _this.data.imgList[index],
      urls: _this.data.imgList
    })
  },
  /**
   * 点击删除图片
   */
  deleteImg: function (e) {
    var _this = this;
    var imgList = _this.data.imgList;
    var index = e.mark.oid       //获取当前点击图片下标
    // var index = e.currentTarget.dataset.oid;      //获取当前点击图片下标
    wx.showModal({
      title: '提示',
      content: '确认要删除该图片吗?',
      success: function (res) {
        if (res.confirm) {
          console.log("点击确定了")
          imgList.splice(index, 1);
        } else if (res.cancel) {
          console.log("点击取消了");
          return false
        }
        _this.setData({
          imgList
        })
      }
    })
  },
  /**
   * 点击删除视频
   */
  deleteVideo: function(e) {
    var _this = this;
    var src = _this.data.src;
    var index = e.mark.oid;      //获取当前点击图片下标
    console.log(index);
    wx.showModal({
      title: '提示',
      content: '确认要删除该视频吗?',
      success: function (res) {
        if (res.confirm) {
          console.log("点击确定了")
          var unsrc = '';
          _this.setData({
            src: unsrc
          })
        } else if (res.cancel) {
          console.log("点击取消了");
          return false
        }
      }
    })
  },
  /**
   * 图片  视频 选择框
   */
  actioncnt: function() {
    var _this = this;
    wx.showActionSheet({
      itemList: ['图片', '视频'],
      success: function(res) {
        if(res.tapIndex == 0) {
          _this.chooseSource()
        }
        if(res.tapIndex == 1) {
          _this.chooseVideo()
        }
      },
      fail: function(res) {
        console.log(res.errMsg)
      }
    })
  },
  /**
   * 选择视频
   */
  chooseVideo: function() {
    var _this = this;
    wx.chooseVideo({
      success: function(res) {
        console.log('111',res);
        _this.setData({
          src: res.tempFilePath,
        })
        _this.uploadvideo()
      }
    })
  },
  /**
   * 上传视频 目前后台限制最大100M, 以后如果视频太大可以选择视频的时候进行压缩
   */
  uploadvideo: function() {
    var self = this;
    var src = this.data.src;
    wx.uploadFile({
      url: "http://192.168.0.195:8291/OnLoad/uploadFile",
      name: 'file',
      methid: 'POST',          // 可用可不用
      filePath: src,
      mutiple:true,  
      formData: {
        'user': 'test'
      },      // 服务器定义key字段名称
      success: function(resp) {
        resp.data = JSON.parse(resp.data).data
        self.setData({
          video:resp.data.split(',')[0],
        })
      },
      fail: function() {
        console.log('接口调用失败')
      }
    })
  },


  addTopic() {
    wx.navigateTo({
      url: '/pages/add-topic/index'
    })
  }
})
